package com.itheima.service;

import com.itheima.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class ServicesDemo {
    private SqlSession Session = null;

    @Before
    public void before() throws IOException {
        //加载核心配置文件
        InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //获取session
        Session = sqlSessionFactory.openSession();

    }

    @After
    public void after() {
        //提交
        Session.commit();
        //释放资源
        Session.close();
    }


    @Test
    public void save() {
        User user = new User();
        user.setUsername("PDD");
        user.setPassword("123");
        Session.insert("userMapper.save", user);
    }

    @Test
    public void findAll() {
        List<User> users = Session.selectList("userMapper.findAll");
        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void findById() {
        User user = Session.selectOne("userMapper.findById", 2);
        System.out.println(user);

    }

    @Test
    public void saveUserReturnId() {
        User user = new User();
        user.setUsername("赵今麦");
        user.setPassword("1234");
        System.out.println(user);
        int insert = Session.insert("userMapper.saveUserReturnId", user);
        System.out.println(insert);
        System.out.println(user);
    }

    @Test
    public void findName() {
        List<User> users = Session.selectList("userMapper.findName", "赵今麦");
        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void findName2() {
        List<User> users = Session.selectList("userMapper.findName2", "%今%");
        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void findCount() {
        int count = Session.selectOne("userMapper.findCount");
        System.out.println(count);
    }

    @Test
    public void saveUserReturnId2() {
        User user = new User();
        user.setId(1);
        user.setUsername("张子枫");
        user.setPassword("1456");
         Session.insert("userMapper.saveUserReturnId2", user);


    }

    @Test
    public void delete() {
        Session.delete("userMapper.delete", 16);

    }
    @Test
    public void update(){
        User user = new User();
        user.setId(1);
        user.setUsername("lili");
        user.setPassword("1321");
         Session.update("userMapper.update", user);
    }


}
